const router = new require('koa-router')();
const TOKEN = '78ccc14881cb0ba6';
const logger = require('self-log').getLogger('index');
const BRANCH_REG = /(.+\/{1})(.+)/;
const { exec } = require('child_process');
const path = require('path');

router.post('/push', async (ctx) => {
  let headerPwd = ctx.header['x-gitee-token'];
  let params = ctx.request.body;
  if (headerPwd === params.password && headerPwd === TOKEN) {
    let name = params.repository.name; // 工程名称
    let branch = params.ref.match(BRANCH_REG)[2]; // 分支

    logger.info(`push ${name} to ${branch}`);

    exec(`sh test.sh ${name} ${branch}`, { cwd: path.join('/data') }, (error, stdout, stderr) => {
      if (error) {
        logger.error(`test.sh exec error: ${error}`);
        return;
      }
      if (stderr) {
        if (stderr.startsWith('From ') && stderr.indexOf('git') !== -1) {
          logger.info('test.sh exec success');
          return;
        }
        logger.warn(`test.sh stderr: ${stderr}`);
      } else {
        logger.info('test.sh exec success');
      }
    });

    ctx.body = 'SUCCESS';
  } else {
    ctx.body = 'TOKEN_ERROR';
  }
});

module.exports = router;
